package com.adcc.monitoragent.mina;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IoHandlerUDP extends IoHandlerAdapter {
	private final static Logger log = LoggerFactory
			.getLogger(IoHandlerUDP.class);
	private MinaListener mListener;
	private long serverErrorTime = 0;
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		log.info("服务器发生异常： {}", cause.getMessage());
		serverErrorTime = System.currentTimeMillis();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		String content = message.toString();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String datetime = sdf.format(new Date());
		log.debug("服务器接收到数据: " + datetime + "\t" + content);
		if (mListener != null) {
			mListener.receive(content);
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		log.debug("服务器发送消息： {}", message);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		log.debug("关闭当前session：{}#{}", session.getId(), session
				.getRemoteAddress());

		CloseFuture closeFuture = session.close(true);
		closeFuture.addListener(new IoFutureListener<IoFuture>() {
			public void operationComplete(IoFuture future) {
				if (future instanceof CloseFuture) {
					((CloseFuture) future).setClosed();
					log.debug("sessionClosed CloseFuture setClosed-->{},",
							future.getSession().getId());
				}
			}
		});
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		log.debug("创建一个新连接：{}", session.getRemoteAddress());
		session.write("welcome to the chat room !");
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		if (status.equals(IdleStatus.BOTH_IDLE)) {
			session.write("心跳消息");
		}
		log.debug("当前连接{}处于空闲状态：{}", session.getRemoteAddress(), status);
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		log.debug("打开一个session：{}#{}", session.getId(), session
				.getBothIdleCount());
	}
	
	/**
	 * 添加UdpListener方法
	 */
	public void addListener(MinaListener listener) {
		if (listener != null)
			this.mListener = listener;
	}
	/**
	 * 服务器端是否异常
	 * @return
	 */
	public boolean isServerOk() {
		return (System.currentTimeMillis() - serverErrorTime) > 10000;
	}
	
}
